package com.example.prompt.service;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.example.prompt.config.AIModelProperties;
import com.example.prompt.dto.PromptRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class PromptService {
    private final AIModelProperties properties;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public String optimizePrompt(PromptRequest request) {
        String apiKey = (request.getApiKey() == null || request.getApiKey().trim().isEmpty()) 
            ? properties.getApiKey() 
            : request.getApiKey();

        // 检查 API Key 是否为空
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new RuntimeException("请在高级设置中输入 API Key，或在系统配置文件中设置默认的 API Key");
        }

        String model = (request.getModel() == null || request.getModel().trim().isEmpty())
            ? properties.getModel()
            : request.getModel();

        String apiUrl = properties.getApiUrl();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        ObjectNode requestBody = objectMapper.createObjectNode();
        requestBody.put("model", model);
        requestBody.putArray("messages")
            .add(objectMapper.createObjectNode()
                .put("role", "system")
                .put("content", "你是一个专业的 Prompt 优化专家，可以帮助用户将简短的任务描述扩充成结构完整的 Prompt。请直接返回优化后的内容，不要添加任何开场白和结束语。"))
            .add(objectMapper.createObjectNode()
                .put("role", "user")
                .put("content", request.getTaskDescription()));

        HttpEntity<ObjectNode> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<JsonNode> responseEntity = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                requestEntity,
                JsonNode.class
            );

            JsonNode response = responseEntity.getBody();
            if (response != null && response.has("choices") && response.get("choices").size() > 0) {
                String content = response.path("choices").get(0).path("message").path("content").asText();
                return cleanupResponse(content);
            } else {
                throw new RuntimeException("API 响应格式不正确");
            }
        } catch (HttpClientErrorException.Unauthorized e) {
            throw new RuntimeException("API 认证失败，请检查 API Key 是否正确", e);
        } catch (Exception e) {
            throw new RuntimeException("调用 API 时发生错误: " + e.getMessage(), e);
        }
    }

    private String cleanupResponse(String content) {
        // 去除开头的客套话
        content = content.replaceAll("^(当然可以！|好的，|这是|以下是|为您提供|我来帮您|我可以帮您|我会帮您|让我为您|我已经|好的，|好的!|当然!|好的。|当然。|好的！|当然！|好的,|当然,)[^\\n]*\\n*", "");
        
        // 去除开头的分隔符
        content = content.replaceAll("^[\\s-_*=#]+\\n*", "");
        
        // 去除结尾的分隔符
        content = content.replaceAll("\\n*[\\s-_*=#]+$", "");
        
        // 去除结尾的客套话
        content = content.replaceAll("\\n*(希望这[^\\n]*|如果您[^\\n]*|请根据[^\\n]*|您可以[^\\n]*|以上[^\\n]*|这样的[^\\n]*)$", "");
        
        // 去除多余的空行
        content = content.replaceAll("\\n{3,}", "\n\n");
        
        // 去除开头和结尾的空白字符
        return content.trim();
    }
}